import Vue from 'vue';
import uniRequest from 'uni-request';
// import store from 'store'
import {
	UserTokenKey,
	BaseUrl,
	WhiteList
} from './config.js'
import {
	CurrentUrl
} from './util.js';

uniRequest.defaults.baseURL = BaseUrl
uniRequest.defaults.headers.post['Content-Type'] = 'application/json';

// 请求拦截
uniRequest.interceptors.request.use(
	request => {
		//配置基本信息
		let token = uni.getStorageSync(UserTokenKey);
		if (token)
			request.headers.common['Authorization'] = token
		return request;
	},
	err => {
		console.log('请求失败');
		return Promise.reject(err);
	}
);
const errorHandle = (status, err) => {
	// console.log('状态码判断', status);
	// console.log(err);
	// 状态码判断
	switch (status) {
		case 401:
			Vue.prototype.$toast('请先登录');
			uni.removeStorageSync(UserTokenKey);
			// toLogin(status);
			break;
		case 500:
			Vue.prototype.$showModal(err);
			break;
		default:
			break;
	}
}
const toLogin = (status) => {
	Vue.prototype.$toast('您还没登录，请先登录');
	setTimeout(() => {
		uni.navigateTo({
			url: '/pages/Login/Login-shortcut'
		})
	}, 1000)
}

// 响应拦截
uniRequest.interceptors.response.use(response => {
	// console.log('返回进入拦截成功--success', response)
	if (response.data.code == 200) {
		let isWhite = WhiteList.find(o => CurrentUrl().indexOf(o) !== -1);
		if (!isWhite) {
			return Promise.resolve(response)
		} else {
			return Promise.resolve(response)
		}
	} else if (response.data.code == 14009 || response.data.code == 14008) {
		const {
			data = {}
		} = response;
		errorHandle(response.data.code, data);
		return Promise.resolve(data);
	} else if (response.data.code == 10800) {
		errorHandle(response.data.code, response.data.msg);
		return Promise.reject(response.data);
	} else if (response.data.code == 10002) {
		const {
			data = {}
		} = response;
		errorHandle(data.code, data.msg);
		return Promise.resolve(response.data);
	} else {
		const {
			data = {}
		} = response;
		// console.log('返回失败', data)
		errorHandle(data.code, data.msg);
		// return Promise.resolve(response.data);
	}
}, error => {
	console.log('返回进入拦截失败--fail', error)
	// const {
	// 	response = {}
	// } = error;
	// const {
	// 	data = {}
	// } = response;
	// errorHandle(data.code, data);
	return Promise.reject(error.data);
});

export default uniRequest